package com.finalist.dao.impl;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import com.finalist.Page;
import com.finalist.Pageable;
import com.finalist.dao.StoreDao;
import com.finalist.entity.Area;
import com.finalist.entity.Store;
import com.finalist.entity.Product.OrderType;

@Repository("storeDaoImpl")
public class StoreDaoImpl extends BaseDaoImpl<Store, Long> implements StoreDao {

	@Override
	public Page<Store> findPage(Store store, Area area, OrderType orderType, Pageable pageable) {
		CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
		CriteriaQuery<Store> criteriaQuery = criteriaBuilder.createQuery(Store.class);
		Root<Store> root = criteriaQuery.from(Store.class);
		criteriaQuery.select(root);
		Predicate restrictions = criteriaBuilder.conjunction();
		if (area != null) {
			restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.equal(root.get("area"), area), criteriaBuilder.like(root.get("area").<String> get("fullName"), "%" + area.getFullName() + "%")));
		}
		if (store != null) {
			if (store.getName() != null) {
				restrictions = criteriaBuilder.like(root.<String> get("name") , "%" + store.getName() + "%");
			}
		}
		
		criteriaQuery.where(restrictions);
		criteriaQuery.orderBy(criteriaBuilder.desc(root.get("id")));
		return super.findPage(criteriaQuery, pageable);
	}

}
